package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.base.RecycleViewDivider;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.ReservedOddBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ReservedActivity extends BaseActivity implements View.OnClickListener {
    private TextView nos_beian;
    private LinearLayout has_beian;
    private RelativeLayout max_buttom;
    private TextView recode_name;
    private TextView time;
    private TextView use_nums;
    private TextView price;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reserved);
      //  MyApplication.getInstance().addDestoryActivity(this, "yusaundan");
        EventBus.getDefault().register(this);

        initAllData();
        initTilte();
        initView();
        // initData();
    }

    private void initAllData() {
        cards = getIntent().getStringExtra("cateId");
    }

    private String cards;

    private void initView() {
        recode_name = (TextView) findViewById(R.id.recode_name);
        nos_beian = (TextView) findViewById(R.id.nos_beian);
        has_beian = (LinearLayout) findViewById(R.id.has_beian);
        max_buttom = (RelativeLayout) findViewById(R.id.max_buttom);
        has_beian.setVisibility(View.GONE);
        max_buttom.setVisibility(View.GONE);
        time = (TextView) findViewById(R.id.time);
        use_nums = (TextView) findViewById(R.id.use_nums);
        //--
        nos_beian.setOnClickListener(this);
        has_beian.setOnClickListener(this);
        max_buttom.setOnClickListener(this);
        price = (TextView) findViewById(R.id.price);
        //--
        findViewById(R.id.history_order).setOnClickListener(this);
        reserved_recycler = (RecyclerView) findViewById(R.id.reserved_recycler);
        reserved_recycler.addItemDecoration(new RecycleViewDivider(this, LinearLayout.HORIZONTAL, R.drawable.line_shape));
        reserved_recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }


    private void initData() {
        recode_name.setText(infos.getProject_name() + "");
        time.setText(infos.getProject_time() + "");
        use_nums.setText("一共有" + infos.getYusuan_times() + "个订单");
        price.setText("￥" + infos.getTotal_fee());
        reserved_recycler.setAdapter(new BaseRVAdapter(this, infos.getData()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_reserved;
            }

            @Override
            public void onBind(final BaseViewHolder viewHolder, final int position) {
                x.image().bind(viewHolder.getImageView(R.id.shop_img), infos.getData().get(position).getImg());
                viewHolder.setTextView(R.id.title, infos.getData().get(position).getPackage_name());
                viewHolder.setTextView(R.id.sku, infos.getData().get(position).getPackage_cate());
                viewHolder.setTextView(R.id.desc, infos.getData().get(position).getPackage_sku_info());
                viewHolder.setTextView(R.id.room_num, infos.getData().get(position).getRoom_number());
                viewHolder.setTextView(R.id.price, "￥" + infos.getData().get(position).getPackage_money());
                viewHolder.setTextView(R.id.shopping_number, "￥" + infos.getData().get(position).getNums());
                final ImageView is_select = viewHolder.getImageView(R.id.is_select);
                if (infos.getData().get(position).isSelect()) {
                    is_select.setImageResource(R.mipmap.ic_choose_li);
                } else {
                    is_select.setImageResource(R.mipmap.ic_choose_nor);
                }
                is_select.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        infos.getData().get(position).setSelect(!infos.getData().get(position).isSelect());
                        if (infos.getData().get(position).isSelect()) {
                            is_select.setImageResource(R.mipmap.ic_choose_li);
                        } else {
                            is_select.setImageResource(R.mipmap.ic_choose_nor);
                        }
                        updatePrice();
                    }
                });


                viewHolder.getTextView(R.id.shopping_number).setText("" + infos.getData().get(position).getNums());
                //
                viewHolder.getImageView(R.id.ll_add).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.ll_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) + 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        infos.getData().get(position).setNums(nums + "");
                        //
                        updatePrice();
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getImageView(R.id.reduce).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.reduce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) - 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        if (nums == 0) {
                            MyToast("再减就没了");
                            nums = 1;
                        }

                        infos.getData().get(position).setNums(nums + "");
                        //
                        updatePrice();
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getTextView(R.id.shopping_number).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(ReservedActivity.this);
                        View view = View.inflate(ReservedActivity.this, R.layout.dialog_edit, null);
                        TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                        TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                        final EditText shopping_number = (EditText) view.findViewById(R.id.shopping_number);
                        shopping_number.setText(infos.getData().get(position).getNums());
                        builder.setView(view);
                        final AlertDialog show = builder.show();
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int nums = Integer.parseInt(infos.getData().get(position).getNums());
                                try {
                                    nums = Integer.parseInt(shopping_number.getText().toString());
                                } catch (Exception e) {
                                    nums = Integer.parseInt(infos.getData().get(position).getNums());
                                }
                                infos.getData().get(position).setNums(nums + "");
                                updatePrice();
                                viewHolder.getTextView(R.id.shopping_number).setText(nums + "");
                                show.dismiss();
                            }
                        });
                        quxaio1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });

                    }
                });
            }

        });
    }

    private void updatePrice() {
        double total = 0;
        for (int i = 0; i < infos.getData().size(); i++) {
            // if (infos.getData().get(i).isSelect()) {
            total += Double.parseDouble(infos.getData().get(i).getPackage_money()) * Double.parseDouble(infos.getData().get(i).getNums());
            // }
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        if (price != null) {
            price.setText("￥" + df.format(total));
        }
    }

    private RecyclerView reserved_recycler;


    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("预算单");
        findViewById(R.id.submit).setOnClickListener(this);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView right = (TextView) findViewById(R.id.submit);
        right.setText("下一步");
    }

    private static final int CODE_RECODES = 438;

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:

                intent = new Intent(this, ReservedDetailActivity.class);
                intent.putExtra("record_id", recordsId + "");
                intent.putExtra("project_name", recode_name.getText().toString());
                ArrayList<ReservedOddBean.InfoEntity.DataEntity> data = new ArrayList<>();
                data.clear();
                data = (ArrayList<ReservedOddBean.InfoEntity.DataEntity>) infos.getData();
                if (data == null || data.size() == 0) {
                    return;
                }
                intent.putExtra("data", data);
                startActivity(intent);
                break;
            case R.id.history_order:
                intent = new Intent(this, HistoryOrderActivity.class);
                ArrayList<ReservedOddBean.InfoEntity.YusuanListEntity> yuSuan = (ArrayList<ReservedOddBean.InfoEntity.YusuanListEntity>) infos.getYusuan_list();
                intent.putExtra("yusuan", yuSuan);
                startActivity(intent);
                break;
            case R.id.nos_beian:
            case R.id.has_beian:
                intent = new Intent(this, AddRecordsCodeActivity.class);
                startActivityForResult(intent, CODE_RECODES);
                break;
        }
    }

    private int recordsId = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CODE_RECODES:
                if (resultCode == RESULT_OK) {
                    has_beian.setVisibility(View.VISIBLE);
                    findViewById(R.id.submit).setVisibility(View.VISIBLE);
                    nos_beian.setVisibility(View.GONE);
                    max_buttom.setVisibility(View.VISIBLE);
                    recordsId = Integer.parseInt(data.getStringExtra("recordsId"));
                    //String name = data.getStringExtra("recordsName");
                    //  recode_name.setText(name + "");
                    upLoadAllInfo();
                }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private ReservedOddBean.InfoEntity infos = new ReservedOddBean.InfoEntity();
    private boolean flag = false;

    private void upLoadAllInfo() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("recordId", recordsId);
        map.put("cartIds", cards);
        showDialog();
        flag = false;
        XUtil.Post(Url.BATH_SEEBUDGETPAGE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        ReservedOddBean bean = gson.fromJson(result, ReservedOddBean.class);
                        infos = bean.getInfo();
                        flag = true;
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                if (flag)
                    initData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }
}
